﻿namespace MeiWinForms;

partial class FormMain
{
    private readonly NotifyIcon _trayIcon = new();
    private readonly ContextMenuStrip _trayMenu = new();

    private void InitTray()
    {
        _trayIcon.Icon = new Icon("mei.ico");
        _trayIcon.Visible = true;
        _trayIcon.Text = Text;

        // 监听托盘图标点击事件
        _trayIcon.Click += TrayIcon_Click;

        // 监听窗体大小改变事件
        Resize += MainForm_Resize;

        _trayMenu.Items.Add("退出", null, ExitMenuItem_Click);
        _trayIcon.ContextMenuStrip = _trayMenu;
    }

    // 窗体大小改变事件
    private void MainForm_Resize(object? sender, EventArgs e)
    {
        // 如果窗口被最小化
        if (WindowState == FormWindowState.Minimized)
        {
            // 隐藏窗体
            Hide();
        }
    }

    // 单击托盘图标恢复窗体
    private void TrayIcon_Click(object? sender, EventArgs e)
    {
        // 显示窗体
        Show();
        WindowState = FormWindowState.Normal;
    }

    private static void ExitMenuItem_Click(object? sender, EventArgs e)
    {
        // 退出应用程序
        Application.Exit();
    }
}